// 防抖和节流函数
const debounce = (fn, delay) => {
  let timer = null;
  return function (...args) {
    if (timer) clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

const throttle = (fn, delay) => {
  let timer = null;
  return function (...args) {
    if (timer) return;
    timer = setTimeout(() => {
      fn.apply(this, args);
      timer = null;
    }, delay);
  };
};

// 自定义指令
export default {
  install(app) {
    // v-debounce 防抖指令
    app.directive('debounce', {
      mounted(el, binding) {
        const { value, arg = 300 } = binding;
        el.addEventListener('click', debounce(value, Number(arg)));
      },
      unmounted(el, binding) {
        el.removeEventListener('click', binding.value);
      },
    });

    // v-throttle 节流指令
    app.directive('throttle', {
      mounted(el, binding) {
        const { value, arg = 300 } = binding;
        el.addEventListener('click', throttle(value, Number(arg)));
      },
      unmounted(el, binding) {
        el.removeEventListener('click', binding.value);
      },
    });
  },
};